package org.web.common.sso.client.biz.impl;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.web.base.domain.ResultDO;
import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.helper.ResultHelper;
import org.web.base.domain.helper.ServiceExceptionHelper;
import org.web.base.helper.HttpHelper;
import org.web.base.helper.PropertiesHelper;
import org.web.base.helper.filter.URIHelper;
import org.web.common.sso.client.domain.SessionAccountDO;
import org.web.common.sso.client.helper.SSOHelper;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ResourceBundle;

@Setter
@Getter
public class DefaultSSOFilter extends SSOAbstractFilter {

    Logger logger = LoggerFactory.getLogger(DefaultSSOFilter.class);

    private String getAccountInfoByTokenURL = null;
    private String getAccountInfoByExchangeTokenURL = null;
    private String getRedirectURL = null;

    @Override
    ResultDO<SessionAccountDO> getSessionByToken(String token) {
        ResultDO<SessionAccountDO> resultDO;
        try {
            String str = HttpHelper.requestByGet(getAccountInfoByTokenURL + "?token=" + token);
            resultDO = SSOHelper.generateSessionAccountByStr(str);
        } catch (Exception e) {
            logger.error("Execute token is " + getAccountInfoByTokenURL + ", token is " + token);
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            resultDO = ResultHelper.buildResultDOByException(e);
        }
        return resultDO;
    }

    @Override
    @SuppressWarnings("unchecked")
    ResultDO<SessionAccountDO> getSessionBySSOExchangeToken(String ssoExchangeToken, CookieRule cookieRule) {
        ResultDO<SessionAccountDO> resultDO;
        try {
            String str = HttpHelper.requestByGet(getAccountInfoByExchangeTokenURL + "?ssoExchangeToken=" + ssoExchangeToken);
            resultDO = SSOHelper.generateSessionAccountByStr(str);
        } catch (Exception e) {
            logger.error("Execute ssoExchangeToken is " + getAccountInfoByExchangeTokenURL + ", ssoExchangeToken is " + ssoExchangeToken);
            logger.error(ServiceExceptionHelper.getExceptionInfo(e));
            resultDO = ResultHelper.buildResultDOByException(e);
        }
        return resultDO;
    }


    @Override
    public void init(FilterConfig filterConfig) {
        super.init(filterConfig);
        ResourceBundle resourceBundle = SSOAbstractFilterConfig.getResourceBundle();
        String ssoServerAddress = PropertiesHelper.getString(resourceBundle, PROPERTIES_SSO_SERVER_ADDRESS, null);
        if (StringUtils.isEmpty(ssoServerAddress)) {
            throw ServiceExceptionHelper.buildServiceException(ResultMessageEnum.INIT_PARAM_NOT_SETTED, PROPERTIES_SSO_SERVER_ADDRESS + "没有设置");
        }

        getAccountInfoByExchangeTokenURL = ssoServerAddress + "/ssoServer/token/getSessionBySSOExchangeToken";
        getAccountInfoByTokenURL = ssoServerAddress + "/ssoServer/token/getSessionByToken";
        getRedirectURL = ssoServerAddress + "/ssoServer/sessionAccount/loginPage";
    }

    @Override
    protected void sendRedirect(HttpServletResponse response) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        if (StringUtils.isNotBlank(request.getQueryString())) {
            response.sendRedirect(getRedirectURL + "?forwardUrl=" + URLEncoder.encode(URIHelper.removeParamForKeys(request.getRequestURL() + "?" + request.getQueryString(),PARAMETER_SSO_EXCHANGE_TOKEN), "UTF-8"));
        } else {
            response.sendRedirect(getRedirectURL + "?forwardUrl=" + request.getRequestURL());
        }
    }

    @Override
    void executeWhenError(HttpServletResponse response) throws IOException {

    }

}
